package com.authine.cloudpivot.web.api.service.impl;



import com.authine.cloudpivot.web.api.bean.RoleAndUser;
import com.authine.cloudpivot.web.api.bean.Users;
import com.authine.cloudpivot.web.api.dao.ExecutiveStaffMapper;
import com.authine.cloudpivot.web.api.dao.ProjectTeamMapper;
import com.authine.cloudpivot.web.api.dao.StoreDetailMapper;
import com.authine.cloudpivot.web.api.domain.dto.UserDTO;
import com.authine.cloudpivot.web.api.service.ProjectTeamService;
import com.authine.cloudpivot.web.api.vo.ExecutiveStaff;
import com.authine.cloudpivot.web.api.vo.StoreDetail;
import com.authine.cloudpivot.web.api.vo.XMQD;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class ProjectTeamServiceImpl implements ProjectTeamService {


    @Autowired
    private ExecutiveStaffMapper  executiveStaffMapper;

    @Autowired
    private  StoreDetailMapper storeDetailMapper;

    @Autowired
    private ProjectTeamMapper projectTeamMapper;

    /**
     * @Description : 获取组建团队中的执行成员列表
     * @param ： projectId
     * @author : Liun
     * @date : 2020/4/14
     */
   @Override
   public List<RoleAndUser> getRoleAndUser(String projectId){
       String parentid=executiveStaffMapper.getProjectTeamId(projectId);
       List<RoleAndUser>  roleAndUserList=new ArrayList<>();
       if(StringUtils.isNotEmpty(parentid)){
           Example example=new Example(ExecutiveStaff.class);
           Example.Criteria  criteria=example.createCriteria();
           criteria.andEqualTo("parentid",parentid);
           example.orderBy("sortkey");
           List<ExecutiveStaff> list=executiveStaffMapper.selectByExample(example);
           if(list.size()>0){
               for(ExecutiveStaff executiveStaff:list){
                   RoleAndUser roleAndUser= new RoleAndUser();
                   BeanUtils.copyProperties(executiveStaff,roleAndUser);
                   String users=executiveStaff.getPerson();
                   String persons=executiveStaff.getPersons();
                   if(!StringUtils.isEmpty(persons)){
                       users= executiveStaffMapper.getUsers(persons);
                   }
                   users=this.createUser(users);
                   roleAndUser.setPerson(users);
                   roleAndUserList.add(roleAndUser);
               }
           }
       }
        return roleAndUserList;
     }

     /**
      * @Description : 生成对应的user返回到前端
      * @param ： persons
      * @author : Liun
      * @date : 2020/4/14
      */
     public String createUser(String persons){

         JSONArray person = JSONArray.fromObject(persons);
         String id;
         List<Users> usersList=new ArrayList<>();
         for(Object personObj:person){
             JSONObject jsonObject2= JSONObject.fromObject(personObj);
             Users users=(Users)JSONObject.toBean(jsonObject2,Users.class);
             id=users.getId();
             Map<String,String> map=executiveStaffMapper.getUsersNameAndImg(id);
             users.setName(map.get("name"));
             users.setImgUrl(map.get("imgUrl"));
             usersList.add(users);
         }
         JSONArray listArray=JSONArray.fromObject(usersList);
         String lastUsers=listArray.toString();
         return lastUsers;
     }

     /**
      * @Description : 批量更换某个城市下的督导
      * @param ： projectId
      * @param ： city
      * @param ： persons
      * @param ： person
      * @author : Liun
      * @date : 2020/4/27
      */
     @Override
     public void updateStoreDetail(String parentIdOld,String parentIdNew,String city){
         //查找到原城市下的所有门店数据
         Example example=new Example(StoreDetail.class);
         Example.Criteria criteria=example.createCriteria();
         criteria.andEqualTo("parentid",parentIdOld);
         criteria.andEqualTo("cityname",city);
         example.orderBy("sortkey");
         List<StoreDetail> storeDetails=storeDetailMapper.selectByExample(example);

         //查找新督导下的该项目的最大sortkey
         Example exampleNew=new Example(StoreDetail.class);
         Example.Criteria criteriaNew=example.createCriteria();
         criteriaNew.andEqualTo("parentid",parentIdNew);
         exampleNew.setOrderByClause("sortKey desc");
         List<StoreDetail> storeDetailsNew=storeDetailMapper.selectByExample(exampleNew);
         BigDecimal bg=new BigDecimal(0);
         BigDecimal bgOne=new BigDecimal(1);
         if(storeDetailsNew.size()>0){
             bg=storeDetailsNew.get(0).getSortkey();
         }

         //添加到新的督导下面
         List<StoreDetail> newStoreDetailList=new ArrayList<>();
         for(StoreDetail storeDetail:storeDetails){
             StoreDetail newStoreDetail=new StoreDetail();
             BeanUtils.copyProperties(storeDetail,newStoreDetail);
             String  uuid = UUID.randomUUID().toString().replace("-","");
             newStoreDetail.setId(uuid);
             newStoreDetail.setParentid(parentIdNew);
             newStoreDetail.setStorestatus("启用");
             bg=bg.add(bgOne);
             newStoreDetail.setSortkey(bg);
             newStoreDetailList.add(newStoreDetail);
         }
         storeDetailMapper.insertNewStoreDetails(newStoreDetailList);
    }


    /**
     * @Description : 添加人员到客服和项目助理角色中去
     * @param ： projectId
     * @param ： role
     * @param ： member
     * @author : Liun
     * @date : 2020/7/22
     */
    @Override
    public void createCustomerAndAssistant(String projectId,String role,String member){
        //id
        String id = UUID.randomUUID().toString().replace("-", "");
        //角色id
        String roleId="";
        List<String> roleIds= projectTeamMapper.getRoleId(role);
        if(roleIds.size()>0 && roleIds.get(0)!=null&&StringUtils.isNotEmpty(roleIds.get(0))){
            roleId=roleIds.get(0);
        }
        //管理范围(FA新零售)
        String ouScope="["+"\"2c928fbb7129a41e01712f0c81ec2ec1\""+"]";

        //获取创建时间
        String createdTime= DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");
        String  creater="2c9280a26706a73a016706a93ccf002b";
        String unitType="USER";

        //回写组织角色
        projectTeamMapper.creatOrgRoleUser(id,createdTime, creater,ouScope,roleId,member,unitType);

        String roleType="";
        if("项目专员".equals(role)){
            roleType="customerS";
        }else if("项目助理".equals(role)){
            roleType="projectAss";
        }



        List<String> userList=projectTeamMapper.selectUsers( roleType,projectId);
        List<UserDTO>  userLists=new ArrayList<>();
        if(userList.size()>0 && userList.get(0)!=null&&StringUtils.isNotEmpty(userList.get(0))){
            userLists=  addUserDTO(userList, userLists,member);
        }else{
            UserDTO userDTO=new UserDTO();
            userDTO.setId(member);
            userDTO.setType(3);
            userLists.add(userDTO);
        }


        List<String> memberList=projectTeamMapper.selectUsers( "memberTotal",projectId);
        List<UserDTO>  memberLists=new ArrayList<>();

        if(memberList.size()>0 && memberList.get(0)!=null&&StringUtils.isNotEmpty(memberList.get(0))){
            memberLists=  addUserDTO(memberList, memberLists,member);
        }else{
            //项目经理
            List<String> subjectPersons=  projectTeamMapper.selectSubjectPerson(projectId);
            if(subjectPersons.size()>0 && subjectPersons.get(0)!=null&&StringUtils.isNotEmpty(subjectPersons.get(0))){
                memberLists=  addUserDTO(subjectPersons, memberLists,member);
            }
        }

        if(userLists.size()>0 && memberLists.size()>0){
            JSONArray listArray=JSONArray.fromObject(userLists);
            String lastUsers=listArray.toString();
            JSONArray listArrayMember=JSONArray.fromObject(memberLists);
            String memberTotal=listArrayMember.toString();
            projectTeamMapper.updateXMQD(projectId,roleType,lastUsers, memberTotal);
        }
    }


    public List<UserDTO> addUserDTO(List<String> personList,List<UserDTO> memberLists,String memberId ){
        String persons=personList.get(0);
        JSONArray jsonArrayPerson = JSONArray.fromObject(persons);
        memberLists = JSONArray.toList(jsonArrayPerson, new UserDTO(), new JsonConfig());
        if(!persons.contains(memberId)){
            UserDTO userDTO=new UserDTO();
            userDTO.setId(memberId);
            userDTO.setType(3);
            memberLists.add(userDTO);
        }
        return memberLists;
    }




    /**
     * @Description :修改项目成员
     * @param ： projectId
     * @param ： role
     * @param ： member
     * @author : Liun
     * @date : 2020/7/29
     */
    @Override
    public void updateCustomerAndAssistant(String projectId,String role,String memberOld,String memberNew){

      List<XMQD>  xmqds=projectTeamMapper.getMemberTotal(projectId);
      if(xmqds.size()>0){
          XMQD xmqd=xmqds.get(0);
          String memberTotal=xmqd.getMemberTotal();
          String customerS=xmqd.getCustomerS();
          String projectAss=xmqd.getProjectAss();
          String users="";
          if(StringUtils.isNotEmpty(memberTotal)&&memberTotal.contains(memberOld)){
              String  memberTotalNew=memberTotal.replace(memberOld,memberNew);
          }
          if(StringUtils.isNotEmpty(customerS)&&customerS.contains(memberOld)&&"客服".equals(role)){
              String  customerSNew=customerS.replace(memberOld,memberNew);
              users=customerSNew;
          }else if(StringUtils.isNotEmpty(customerS)&&!customerS.contains(memberOld)&&"客服".equals(role)){
              users =customerS;
          }
          if(StringUtils.isNotEmpty(projectAss)&&projectAss.contains(memberOld)&&"项目助理".equals(role)){
              String  projectAssNew=projectAss.replace(memberOld,memberNew);
              users=projectAssNew;
          }else if(StringUtils.isNotEmpty(projectAss)&&!projectAss.contains(memberOld)&&"项目助理".equals(role)){
              users=projectAss;
          }
          projectTeamMapper.updateXMQD(projectId,role,users,memberTotal);
      }


    }







}



